//
//  TcpClient.m
//  ConnectTest
//
//  Created by  SmallTask on 13-8-15.
//
//

#import "TcpClient.h"
#import "GCDAsyncSocket.h"
//#import "DDLog.h"
//#import "DDTTYLogger.h"

// Log levels: off, error, warn, info, verbose
//static const int ddLogLevel = LOG_LEVEL_INFO;

#define USE_SECURE_CONNECTION 0
#define ENABLE_BACKGROUNDING  0

#if USE_SECURE_CONNECTION
#define HOST @"www.paypal.com"
#define PORT 443
#else
#define HOST @"192.168.254.2"
#define PORT 55184
#endif


//static  NSInteger   readNoDataCounts = 0;

@interface TcpClient()
{
    dispatch_source_t timer_sendTestPacket;//发心跳包或其他命令定时器
    dispatch_source_t timer_receiveTestPacket;//接收服务端反馈的命令定时器
}

@end

@implementation TcpClient
@synthesize asyncSocket;

+ (TcpClient *)sharedInstance;
{
    static TcpClient *_sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[TcpClient alloc] init];
    });
    
    return _sharedInstance;
}


-(id)init;
{
    self = [super init];
    recivedArray = [NSMutableArray arrayWithCapacity:10];
    return self;
}

-(void)setDelegate_ITcpClient:(id<ITcpClient>)_itcpClient;
{
    itcpClient = _itcpClient;
}

-(void)openTcpConnection:(NSString*)host port:(NSInteger)port;
{	_serverHost = host;
    _serverPort = port;
	dispatch_queue_t mainQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
	asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:mainQueue];
    [asyncSocket setAutoDisconnectOnClosedReadStream:NO];
#if USE_SECURE_CONNECTION
	{
		NSString *host = HOST;
		uint16_t port = PORT;
		
		DDLogInfo(@"Connecting to \"%@\" on port %hu...", host, port);
		self.viewController.label.text = @"Connecting...";
		
		NSError *error = nil;
		if (![asyncSocket connectToHost:@"www.paypal.com" onPort:port error:&error])
		{
			DDLogError(@"Error connecting: %@", error);
			self.viewController.label.text = @"Oops";
		}
	}
#else
    {
		NSError *error = nil;
		if (![asyncSocket connectToHost:host onPort:port error:&error])
		{
        
        }
	}
#endif
}
//发送消息
-(void)writeString:(NSString*)datastr;
{
    NSString *requestStr = [NSString stringWithFormat:@"%@\r\n",datastr];
    
    NSData *requestData = [requestStr dataUsingEncoding:NSUTF8StringEncoding];
    [self writeData:requestData];
}

-(void)writeData:(NSData*)data;
{
    TAG_SEND++;
    [asyncSocket writeData:data withTimeout:-1. tag:TAG_SEND];
}

-(void)read;
{
    [asyncSocket readDataToData:[GCDAsyncSocket CRLFData] withTimeout:-1 tag:0];
//    [asyncSocket readDataToData:[GCDAsyncSocket ZeroData] withTimeout:-1 tag:0];
//    [asyncSocket readDataToLength:1 withTimeout:-1 tag:0];
}

-(long)GetSendTag;
{
    return TAG_SEND;
}

-(long)GetRecivedTag;
{
    return TAG_RECIVED;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#pragma mark Socket Delegate
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
	//DDLogInfo(@"socket:%p didConnectToHost:%@ port:%hu", sock, host, port);
//	self.viewController.label.text = @"Connected";
	
    //	DDLogInfo(@"localHost :%@ port:%hu", [sock localHost], [sock localPort]);
    [self read];
	
#if USE_SECURE_CONNECTION
	{
		// Connected to secure server (HTTPS)
        
#if ENABLE_BACKGROUNDING && !TARGET_IPHONE_SIMULATOR
		{
			// Backgrounding doesn't seem to be supported on the simulator yet
			
			[sock performBlock:^{
				if ([sock enableBackgroundingOnSocket])
					DDLogInfo(@"Enabled backgrounding on socket");
				else
					DDLogWarn(@"Enabling backgrounding failed!");
			}];
		}
#endif
        NSMutableDictionary *settings = [NSMutableDictionary dictionaryWithCapacity:3];
		[settings setObject:@"www.paypal.com"
					 forKey:(NSString *)kCFStreamSSLPeerName];
		DDLogInfo(@"Starting TLS with settings:\n%@", settings);
		
		[sock startTLS:settings];
		
		// You can also pass nil to the startTLS method, which is the same as
		
	}
#else
	{
		// Connected to normal server (HTTP)
		
#if ENABLE_BACKGROUNDING && !TARGET_IPHONE_SIMULATOR
		{
			// Backgrounding doesn't seem to be supported on the simulator yet
			
			[sock performBlock:^{
				if ([sock enableBackgroundingOnSocket])
					DDLogInfo(@"Enabled backgrounding on socket");
				else
					DDLogWarn(@"Enabling backgrounding failed!");
			}];
		}
#endif
	}
#endif
    
    //模拟发送一条数据
//    NSString *requestStr = [NSString stringWithFormat:@"GET / HTTP/1.1\r\nHost: %@\r\n\r\n", HOST];
//	NSData *requestData = [requestStr dataUsingEncoding:NSUTF8StringEncoding];
//    
//    [sock writeData:requestData withTimeout:20. tag:1];
    
    
}

- (void)socketDidSecure:(GCDAsyncSocket *)sock
{
	//DDLogInfo(@"socketDidSecure:%p", sock);
//	self.viewController.label.text = @"Connected + Secure";
	
	NSString *requestStr = [NSString stringWithFormat:@"GET / HTTP/1.1\r\nHost: %@\r\n\r\n", HOST];
	NSData *requestData = [requestStr dataUsingEncoding:NSUTF8StringEncoding];
	
	[sock writeData:requestData withTimeout:-1 tag:0];
	[sock readDataToData:[GCDAsyncSocket CRLFData] withTimeout:-1 tag:0];
}

- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [itcpClient OnSendDataSuccess:[NSString stringWithFormat:@"tag:%li",tag]];
    });
}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
	NSString *httpResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    TAG_RECIVED = tag;
    
    if(![httpResponse isEqualToString:@""] && httpResponse!=nil)
        [recivedArray addObject:httpResponse];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        //
        [itcpClient OnReciveData:httpResponse];
    });
    [self read];
}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
//    [itcpClient OnConnectionError:err];
	//DDLogInfo(@"socketDidDisconnect:%p withError: %@", sock, err);
    dispatch_async(dispatch_get_main_queue(), ^{
        NSError *error = nil;
        [asyncSocket connectToHost:_serverHost onPort:_serverPort error:&error];
        [itcpClient OnConnectionError:err];
    });
}

- (void)socketDidCloseReadStream:(GCDAsyncSocket *)sock
{
    
}


-(void)sendTestPacketData:( NSString *)sendData
{
    /***********进入此函数：说明网络状态良好************/
    if(isHaveDisconnect == YES)
    {
        PostNoticeObserver(@"NetworkSignalNotice", @(0));
    }
    /**********************************************/
    
    __block NSString *requestStr = [NSString stringWithString:sendData];
    
    timer_sendTestPacket = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0));
    dispatch_source_set_timer(timer_sendTestPacket, DISPATCH_TIME_NOW, 15ull * NSEC_PER_SEC, 5ull * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer_sendTestPacket, ^{
        NSLog(@"write!");
        [self writeString:requestStr];
        
    });
    
    dispatch_resume(timer_sendTestPacket);
    
}



@end
